package chat

// ============================================================================

// circular queue for recent chat records
type records_t struct {
	A    []*chat_entry_t
	head int // newest entry. advance the ptr to add new entry
	tail int // oldest entry. pointed data is unusable
	n    int // capacity
}

// ============================================================================

func new_records(n int) *records_t {
	n++ // one more space to distinguish 'empty' and 'full'
	return &records_t{
		A:    make([]*chat_entry_t, n),
		head: 0,
		tail: 0,
		n:    n,
	}
}

func (self *records_t) Add(e *chat_entry_t) {
	// advance head ptr and set the entry
	self.head = (self.head + 1) % self.n
	self.A[self.head] = e

	// if full, advance tail
	if self.head == self.tail {
		self.tail = (self.tail + 1) % self.n
	}
}

func (self *records_t) Each(f func(e *chat_entry_t)) {
	// check empty
	if self.head == self.tail {
		return
	}

	// each
	i := self.tail
	for {
		i = (i + 1) % self.n
		f(self.A[i])

		// if i reaches head. there's no more valid entries
		if i == self.head {
			break
		}
	}
}
